package com.itboye.ihomebank.adapter;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.itboye.ihomebank.R;
import com.itboye.ihomebank.bean.QianYueManageBean;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.bean.WoDeFangYuanBean;
import com.itboye.ihomebank.constants.NetPublicConstant;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.activity.homefragment.ActivityFuYongOne;
import com.itboye.ihomebank.presenter.HousePresenter;
import com.itboye.ihomebank.presenter.UserPresenter;
import com.itboye.ihomebank.activity.qianyue.HeTongYanZhengActivity;
import com.itboye.ihomebank.activity.qianyue.OrderDetailActivity;
import com.itboye.ihomebank.activity.qianyue.ZhongZhiHeTongActivity;
import com.itboye.ihomebank.activity.qianyue.ZiChanQingDanActivity;
import com.itboye.ihomebank.support.commonadapter.MutiplyCommonAdapter;
import com.itboye.ihomebank.support.commonadapter.ViewHolder;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.WriteZhangHaoPopupWindow;
import com.itboye.ihomebank.util.XImageLoader;
import com.itboye.ihomebank.zjtlcb.lnd.livenessdetector.activity.MainLiveActivity;

import java.util.Iterator;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/***
 * 签约管理(已完成)
 *
 * @author dsawe
 */
public class QianYueAdapterTwo extends MutiplyCommonAdapter<QianYueManageBean> implements Observer {
    private List<QianYueManageBean> orderQueryModel;
    Activity context;
    private int type;
    protected String uid;
    protected String password;
    UserPresenter userPresenter;
    HousePresenter mHousePresenter;
    protected String money;
    String tempContractNo;
    protected WriteZhangHaoPopupWindow mCameraPopupWindow;
    EditText pass;
    String role;
    UserPresenter presenter;
    String tempHouseNo="";
    public void setRole(String role) {
        this.role = role;
    }

    public QianYueAdapterTwo(Activity context, List<QianYueManageBean> datas,
                             int... layoutId) {
        super(context, datas, layoutId);
        this.orderQueryModel = datas;
        this.context = context;
        uid = SPUtils.get(context, null, SPContants.USER_ID, "") + "";
        userPresenter = new UserPresenter(this);
        mHousePresenter = new HousePresenter(this);
    }

    @Override
    public int getItemViewType(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public void getItemPosition(int position) {
        // TODO Auto-generated method stub

    }

    @Override
    public void convert(final ViewHolder holder, final QianYueManageBean t, int type,
                        int position) {
        // String shenfen = t.getUserType();
        holder.setText(R.id.contract_no, "合同号:" + t.getContractNo());// contract_no
        holder.setText(R.id.home_title, t.getTitle());
        holder.setText(R.id.home_xq, t.getHouseHall() + "室" + t.getHouseRoom()
                + "厅  " + t.getHouseArea() + "m²");
        holder.setText(R.id.txt_money, Double.parseDouble(t.getRent()) / 100 + "元/月");
        XImageLoader.load(NetPublicConstant.IMAGE_URL + t.getImgId(),
                (ImageView) holder.getView(R.id.home_adapter));
        if (t.getUserType().equals("lesser")) {//为房东
            holder.setVisible(R.id.iv_reddot,true);
            holder.setText(R.id.txt_detail, "查看详情");
            if (t.getPay_brokerage().equals("0")) {//1已付佣金 0没有
                holder.setText(R.id.txt_fuyong, "付佣金");
                holder.setVisible(R.id.txt_fuyong, true);
            } else {
                holder.setVisible(R.id.txt_fuyong, false);
            }
            if (t.getCan_write_facility().equals("1")){//是否可以填写资产清单 0或1
                holder.setVisible(R.id.txt_zichan, true);
                holder.setVisible(R.id.rl_zichan,true);
                holder.setText(R.id.txt_zichan, "附件单");
            }else{
                holder.setVisible(R.id.rl_zichan,false);
                holder.setVisible(R.id.txt_zichan, false);
            }
            if (t.getStatus().equals("0")) {//合同正常状态
                holder.setVisible(R.id.img_yinchuo,false);
                String broker = (String) SPUtils.get(context, null, SPContants.BrokerValidate, "");
                if (t.getTerminate_apply().equals("1") && !broker.equals("1")) {//1:有申请合同终止，并且不是经纪人,需要确认或否决
                    holder.setText(R.id.txt_zhiyue, "同意和拒绝");
                    holder.setVisible(R.id.txt_zhiyue, true);
                } else {
                    holder.setVisible(R.id.txt_zhiyue, false);
                }

                if(t.getOverdue().equals("1")){//已逾期
                    holder.setVisible(R.id.tex_overdue,true);
                    holder.setText(R.id.tex_overdue,"逾期催租");
                    if (t.getCan_notify().equals("1")){
                        ((TextView)holder.getView(R.id.tex_overdue))
                                .setBackground(context.getResources().getDrawable(R.drawable.shape_overdue_red));
                        ((TextView)holder.getView(R.id.tex_overdue)).setEnabled(true);

                    }else {
                        ((TextView)holder.getView(R.id.tex_overdue))
                                .setBackground(context.getResources().getDrawable(R.drawable.shape_overdue_gray));
                        ((TextView)holder.getView(R.id.tex_overdue)).setEnabled(false);
                    }
                }else{
                    holder.setVisible(R.id.tex_overdue,false);
                }


            } else {//终止的合同
                holder.setVisible(R.id.txt_zhiyue, false);
                holder.setVisible(R.id.tex_overdue,false);
                holder.setVisible(R.id.iv_reddot,false);
                holder.setText(R.id.txt_zichan, "上架");
                holder.setVisible(R.id.txt_zichan, true);
                holder.setVisible(R.id.img_yinchuo,true);
            }

        } else {//为租客

            holder.setVisible(R.id.iv_reddot,false);
            if (t.getStatus().equals("0")) {//合同正常状态
                if (t.getContract_type().equals("4")){
                    holder.setText(R.id.txt_detail, "支付详情");
                }else {
                    holder.setText(R.id.txt_detail, "支付租金");
                }
                holder.setText(R.id.txt_detail, "支付租金");
                holder.setText(R.id.txt_zhiyue, "终止合同");
                holder.setVisible(R.id.img_yinchuo,false);
                holder.setVisible(R.id.txt_zhiyue, true);
                holder.setVisible(R.id.txt_fuyong, false);
                holder.setVisible(R.id.tex_overdue,false);
            } else {

                if (t.getContract_type().equals("4")){
                    holder.setText(R.id.txt_detail, "支付详情");
                }else {
                    holder.setText(R.id.txt_detail, "支付租金");
                }
                holder.setVisible(R.id.img_yinchuo,true);
                holder.setVisible(R.id.txt_fuyong, false);
                holder.setVisible(R.id.tex_overdue,false);
                holder.setVisible(R.id.txt_zhiyue, false);
            }
            if (t.getTerminate_apply().equals("1") ) {//已申请过申请合同终止 等待房东或经纪人同意或否决
                holder.setVisible(R.id.txt_zhiyue, false);
            } else {
                holder.setVisible(R.id.txt_zhiyue, true);
            }

            if (t.getCan_write_facility().equals("1")){//是否可以填写资产清单 0或1
                holder.setVisible(R.id.txt_zichan, true);
                holder.setVisible(R.id.rl_zichan,true);
                holder.setText(R.id.txt_zichan, "确认附件单");

            }else{
                holder.setVisible(R.id.txt_zichan, false);
            }
        }
        //填写资产清单
        holder.setOnClickListener(R.id.txt_zichan, position, new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (t.getUserType().equals("lesser")) {//为房东

                    if (t.getStatus().equals("0")) {//状态正常
                        Intent intent = new Intent(context,ZiChanQingDanActivity.class);
                        intent.putExtra("contractNo", t.getContractNo());
                        context.startActivity(intent);
                    }else {//终止合同 上架
                        tempHouseNo=t.getHouseNo();
                        mHousePresenter.shangjia(uid, t.getHouseNo());
                    }

                }else{//为房东（确认资产清单）
                    userPresenter.querenZichan(uid,t.getContractNo(),"0");
                }
            }
        });
        //终止合同
        holder.setOnClickListener(R.id.txt_zhiyue, position, new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (t.getUserType().equals("lesser")) {
                    Intent intent = new Intent(context,
                            HeTongYanZhengActivity.class);
                    intent.putExtra("contractNo", t.getContractNo());
                    context.startActivity(intent);
                } else {
                    Intent intent = new Intent(context,
                            ZhongZhiHeTongActivity.class);
                    intent.putExtra("contractNo", t.getContractNo());
                    context.startActivity(intent);
                }
            }
        });
        holder.setOnClickListener(R.id.txt_detail, position,
                new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub

                        Intent intent = new Intent(context,
                                OrderDetailActivity.class);
//                        Intent intent= new Intent(context, MainLiveActivity.class);
//                        if (t.getIs_bank_stage().equals("0")||t.getIs_bank_stage().equals("")){
//
//                        }else {
//                           intent.putExtra("isbank",1);
//
//                        }

                        intent.putExtra("contractNo", t.getContractNo());
                        context.startActivity(intent);
                    }
                });
        //付佣金
        holder.setOnClickListener(R.id.txt_fuyong, position,
                new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        tempContractNo = t.getContractNo();
                        mCameraPopupWindow = new WriteZhangHaoPopupWindow(context,
                                onclickListener);
                        pass = (EditText) mCameraPopupWindow.getContentView()
                                .findViewById(R.id.pass);
                        mCameraPopupWindow.setBackgroundDrawable(new BitmapDrawable());
                        mCameraPopupWindow.setFocusable(true);
                        mCameraPopupWindow.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
                        mCameraPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
                        mCameraPopupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
                    }
                });
        //逾期催租
        holder.setOnClickListener(R.id.tex_overdue, position,
                new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        tempContractNo = t.getContractNo();
                        Log.e("tempContractNo==",t.toString());
                        mHousePresenter.remindOverdue(tempContractNo);
                    }
                });
    }


    protected OnClickListener onclickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (v.getId() == R.id.btn_ok) {
                String phone = pass.getText().toString();
                if (phone.equals("")) {
                    ByAlert.alert("请输入对方账户");
                    return;
                }
                mCameraPopupWindow.dismiss();
                Intent intent = new Intent(context, ActivityFuYongOne.class);
                intent.putExtra("phone", phone);
                intent.putExtra("contractNo", tempContractNo);
                if (role.equals("jingjiren")) {
                    intent.putExtra("leixing", "1");
                } else {
                    intent.putExtra("leixing", "2");
                }
                context.startActivity(intent);

            } else if (v.getId() == R.id.btn_cancel) {
                mCameraPopupWindow.dismiss();
            }
        }
    };

    public void setStatus(int type) {
        this.type = type;
    }



    @Override
    public void update(Observable observable, Object data) {
        // TODO Auto-generated method stub
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            if (entity.getEventType() == UserPresenter.qingdan_success) {
                ByAlert.alert(entity.getData());
                notifyDataSetChanged();
                context.sendBroadcast(new Intent("showRedDot"));
            } else if (entity.getEventType() == UserPresenter.qingdan_fail){
                ByAlert.alert(entity.getData());
            } else if (entity.getEventType() == HousePresenter.remindOverdue_success){
                mHousePresenter.qianYueGuanLi(uid,1+"");
                ByAlert.alert("操作成功");
            } else if (entity.getEventType() == HousePresenter.remindOverdue_fail){
                ByAlert.alert(entity.getMsg());

            } else if (entity.getEventType() == HousePresenter.qianYueGuanLiOne_success) {
                orderQueryModel.clear();
                orderQueryModel.addAll((List<QianYueManageBean>) entity.getData());
                notifyDataSetChanged();
            }else if (entity.getEventType() == HousePresenter.qianYueGuanLiOne_fail){
                ByAlert.alert(entity.getMsg());

            }else if (entity.getEventType() == HousePresenter.shangJia_fail) {

                ByAlert.alert(entity.getData());
            } else if (entity.getEventType() == HousePresenter.shangJia_success) {
                Iterator<QianYueManageBean> iterator = orderQueryModel.iterator();
                while (iterator.hasNext()) {
                    QianYueManageBean woDeFangYuanBean = (QianYueManageBean) iterator
                            .next();
                    if (tempHouseNo.equals(woDeFangYuanBean.getHouseNo())) {
                        iterator.remove();
                        notifyDataSetChanged();
                        break;
                    }
                }

            }
        }
    }
}
